package com.foxmail.aroundme.boring.adapter.viewpage;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;


import com.foxmail.aroundme.boring.bean.channel.NewsChannelBean;
import com.foxmail.aroundme.boring.module.news.main.ui.NewsListFragment;

import java.util.ArrayList;
import java.util.List;


/**
 * An example for using PagerSlidingTabStrip.
 */
public class NewsChannelTitlePagerAdapter extends NewsChannelStatePagerAdapter {

    private List<NewsChannelBean> mChannels;


    public NewsChannelTitlePagerAdapter(FragmentManager fm, List<NewsChannelBean> channelBeanList) {
        super(fm);
        this.mChannels = channelBeanList;
        initChannel();
    }

    @Override
    public CharSequence getPageTitle(int position) {
        int size = count();
        if (position >= size) {
            return "";
        }
        return mChannels.get(position).name;
    }

    private void initChannel() {
        List<Fragment> fragments = new ArrayList<Fragment>();
        for (NewsChannelBean channelBean : mChannels) {
            Fragment fragment = NewsListFragment.newInstance(channelBean.id, channelBean.name);
            fragments.add(fragment);
        }
        addPageFragments(fragments);
    }

    public void insertPageFragment(NewsChannelBean bean) {
        int size = count();
        if (bean.defaultIndex < 0 || bean.defaultIndex >= size) {
            return;
        }
        mChannels.add(bean.defaultIndex, bean);
        Fragment fragment = NewsListFragment.newInstance(bean.id, bean.name);
        insertPageFragment(fragment, bean.defaultIndex);
    }

    private int count() {
        if (mChannels == null || mChannels.isEmpty()) {
            return 0;
        }
        return mChannels.size();
    }

    /**
     * 获取当前频道数据 多线程处理可能会出现异常
     *
     * @return
     */
    public List<NewsChannelBean> getCurrentChannels() {
        return this.mChannels;
    }
}
